package com.laiat.location;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.laiat.location.activity.PrefsActivity;
import com.laiat.location.service.SendLocationService;

public class LocationGmailerApplication extends Application {
	private static final String TAG = LocationGmailerApplication.class.getSimpleName();

	private SharedPreferences prefs;
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(TAG, "onCreated");
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}
	
	public void resetUpdateAlarm() {
		Context context = getApplicationContext();
		cancelUpdateAlarm();

		// Create the pending intent
		PendingIntent pendingIntent = createUpdateAlarmPendingIntent();

		// Check if we should do start update service
		long updateInterval = Integer.parseInt(getPrefs().getString(PrefsActivity.KEY_SEND_LOCATION_INTERVAL, 
																    Integer.toString(getResources().getInteger(R.integer.defaultSendLocationInterval))));

		// Setup alarm service to wake up and start service periodically
		//FIXME:  add permissions?
		//get alarm manager
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, updateInterval, pendingIntent);
	}
	
	public boolean cancelUpdateAlarm() {
		Context context = getApplicationContext();
		// Create the pending intent
		PendingIntent pendingIntent = createUpdateAlarmPendingIntent();

		//get alarm manager
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		// Cancel alarms
		try {
		    alarmManager.cancel(pendingIntent);
		    return true;
		} catch (Exception e) {
		    Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
		    return false;
		}
	}
	
	public PendingIntent createUpdateAlarmPendingIntent() {
		Context context = getApplicationContext();
		Intent intent = new Intent(context, SendLocationService.class);
		return PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	}
	
	public SharedPreferences getPrefs() {
		return prefs;
	}

}
